﻿using FarPoint.Web.Spread;
using System;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ControlExplorer.samples.OrderEntry
{
  public partial class Overview : SpreadDemoPage
  {
    DataSet DataSetPubs1 = new DataSet();
		StyleInfo style = new StyleInfo();
		string sqlstr;
		int fpRecCnt;
		string[,] tempcart = new string[51, 5];
		FarPoint.Web.Spread.Model.DefaultSheetDataModel model;
		FarPoint.Web.Spread.Model.DefaultSheetDataModel cartmodel;
    string sqlConString;

		DbProviderFactory factory;
		#region " Web Form Designer Generated Code "

		//This call is required by the Web Form Designer.
		[System.Diagnostics.DebuggerStepThrough()]

		private void InitializeComponent()
		{
		}

		private void Page_Init(System.Object sender, System.EventArgs e)
		{
			//CODEGEN: This method call is required by the Web Form Designer
			//Do not modify it using the code editor.
			InitializeComponent();
		}

		#endregion
		

		private void Page_Load(System.Object sender, System.EventArgs e)
		{
            this.FpSpread1.UseClipboard = false;
            //Put user code to initialize the page here

			//Store the database path in a session variable
			if (Session["fpdbpath"] == null) {
        string dbpath = Path.Combine(Server.MapPath("~/App_Data"), "SpreadWebDB.mdb");
				Session["fpdbpath"] = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", dbpath);
			}
      
			sqlConString = Session["fpdbpath"] as string;

			//Populate Spread
			GetData();

			if (this.InIE9PlusCompatView()) {
				foreach (FarPoint.Web.Spread.FpSpread spread in this.GetSpreads(this)) {
					FarPoint.Web.Spread.SheetView activeSheet = spread.ActiveSheetView;
					FarPoint.Web.Spread.Border border = activeSheet.DefaultStyle.Border;
					if (border == null || border.IsEmpty) {
						activeSheet.DefaultStyle.Border = new FarPoint.Web.Spread.Border(BorderStyle.Solid, activeSheet.GridLineColor, 1);
					}
				}
			}
		}

		public void DisplayCart()
		{
			int i = 0;
			int rownum = 0;
			string strDesc = null;
			decimal ordertot = 0;
			int intcnt = 0;

			intcnt = 0;

			//Get the cart count
			if (Information.IsArray(Session["cart"])) {
				while (!string.IsNullOrEmpty(((string[,])Session["cart"])[intcnt, 0]) & intcnt <= Information.UBound(Session["cart"])) {
					intcnt += 1;
				}
			}
			intcnt += 4;
			cartmodel = new FarPoint.Web.Spread.Model.DefaultSheetDataModel(intcnt, 1);
			//rows, columns

			//INIT THE CART SPREAD
			sscart.HorizontalScrollBarPolicy = ScrollBarPolicy.AsNeeded;
			sscart.VerticalScrollBarPolicy = ScrollBarPolicy.AsNeeded;
			sscart.Width = System.Web.UI.WebControls.Unit.Pixel(100);
			sscart.Sheets[0].DataModel = cartmodel;
			sscart.Sheets[0].GridLines = GridLines.None;
			sscart.Sheets[0].PageSize = intcnt;
			sscart.Sheets[0].OperationMode = OperationMode.ReadOnly;
			sscart.CommandBar.Visible = false;

			sscart.BorderStyle = BorderStyle.Inset;

			SetStyleButtonLink(0, "yourcart", "cart.aspx");

			i = 0;
			rownum = 1;
			ordertot = 0;
			SetStyleCartItems(rownum);

			if (null == Session["cart"]) {
				cartmodel.SetValue(rownum, 0, "您的购物车是空的！");
				rownum = rownum + 1;
			} else {
        string[,] sessionCart = (string[,])Session["cart"];
        while (!string.IsNullOrEmpty(sessionCart[i, 0]) & i <= Information.UBound(sessionCart))
        {
					if (rownum == sscart.Rows.Count)
						sscart.Rows.Count = sscart.Rows.Count + 1;

					SetStyleCartItems(rownum);
          string desc = (string)sessionCart[i, 1];
          strDesc = desc.Substring(0, Math.Min(desc.Length, 10)) + "..";
          cartmodel.SetValue(rownum, 0, sessionCart[i, 3] + " " + strDesc);
					//qty + Desc.
          ordertot += decimal.Parse(sessionCart[i, 3]) * decimal.Parse(sessionCart[i, 2]);

					i = i + 1;
					rownum = rownum + 1;
				}

			}
			rownum = rownum + 1;
			if (rownum == sscart.Rows.Count)
				sscart.Rows.Count = sscart.Rows.Count + 1;
			SetStyleCartItems(rownum);
      cartmodel.SetValue(rownum, 0, Strings.FormatCurrency(ordertot, 2));
			//qty + Desc.

			rownum = rownum + 1;
			if (rownum == sscart.Rows.Count)
				sscart.Rows.Count = sscart.Rows.Count + 1;
			SetStyleButtonLink(rownum, "checkout", "checkout.aspx");

			sscart.Visible = true;


		}

		public void SetStyleButtonLink(int row, string fppict, string imgurl)
		{
			style = new StyleInfo();
			style.Reset();
			HyperLinkCellType imgType = new HyperLinkCellType(imgurl, "images/" + fppict + ".jpg", "_self");
			style.CellType = imgType;
			sscart.ActiveSheetView.SetStyleInfo(row, 0, style);

		}

		public void SetStyleCartItems(int row)
		{
			style = new StyleInfo();
			style.Reset();
			style.Font.Italic = true;
      style.Font.Size = FontUnit.Point(8);
			style.HorizontalAlign = HorizontalAlign.Left;
			sscart.ActiveSheetView.SetStyleInfo(row, 0, style);
		}

		public void SetStyleCartHeader(int row)
		{
			style = new StyleInfo();
			style.Reset();
			style.BackColor = Color.Teal;
			style.ForeColor = Color.White;
			style.Font.Bold = true;
      style.Font.Size = FontUnit.Point(10);
			style.HorizontalAlign = HorizontalAlign.Center;
			sscart.ActiveSheetView.SetStyleInfo(row, 0, style);
		}
    
		public void GetData()
		{
			string strresult = null;
			string cbslection = null;
			string sqlcnt = null;
			string btnstr = null;
			int rowcnt = 0;
			int bookcnt = 0;
			int ssrowcnt = 0;
			int imagecolnum = 0;
			int intbreakcol = 0;
			decimal unitprice = 0;

			sqlstr = "SELECT titles.title_id, titles.title, titles.pub_id, publishers.pub_name, titles.price, titles.notes, publishers.pub_id AS Expr1 FROM titles INNER JOIN publishers ON titles.pub_id = publishers.pub_id";
			sqlcnt = "SELECT COUNT(*) AS Expr1 FROM titles";

			//By Publisher
			if (cbPubs.SelectedItem.Value != "All") {
				sqlstr += " where titles.pub_id = '" + cbPubs.SelectedItem.Value + "'";
				sqlcnt += " where titles.pub_id = '" + cbPubs.SelectedItem.Value + "'";
			}

			DbConnection connection1 = DBHelper.CreateConnection(sqlConString);
			DbCommand dbCmd = connection1.CreateCommand();
			dbCmd.CommandText = sqlstr;

			try {
				connection1.Open();
			} catch (DbException ex) {
				lbNoMatch.Font.Bold = true;
				lbNoMatch.ForeColor = Color.Red;
				lbNoMatch.Text = "ERROR: The specified database path could not be found. Please update the database location in the default.aspx.vb page (Page_Load event).";
				sscart.Visible = false;
				FpSpread1.Visible = false;
				return;
			}

			DbDataReader objDataReader = dbCmd.ExecuteReader();

			//Get the record count
			fpRecCnt = GetRecordCount(sqlcnt);
			intbreakcol = fpRecCnt / 2;
			lbNoMatch.Text = "Your search found " + fpRecCnt + " matching books";

			//Set the Spreadsheet data model
			ssrowcnt = (intbreakcol + 1) * 6;
			model = new FarPoint.Web.Spread.Model.DefaultSheetDataModel(ssrowcnt, 5);
			//rows, columns

			//Disble View State
			FpSpread1.EnableViewState = false;
			FpSpread1.Sheets[0].DataModel = model;
			FpSpread1.Sheets[0].GridLines = GridLines.None;
			FpSpread1.Sheets[0].PageSize = ssrowcnt;

			FpSpread1.Sheets[0].OperationMode = OperationMode.ReadOnly;

			FpSpread1.Sheets[0].ColumnHeader.Visible = false;
			FpSpread1.Sheets[0].RowHeader.Visible = false;
			FpSpread1.BorderStyle = BorderStyle.None;
			FpSpread1.CommandBar.Visible = false;

			//Init the default style
			InitSpreadStyle();

			rowcnt = 0;
			imagecolnum = 0;
			bookcnt = 0;

			if (objDataReader.Read() == false) {
				lbNoMatch.Text = lbNoMatch.Text + " none";
				lbNoMatch.Visible = true;
				return;
			}

			while (objDataReader.Read()) {
				if (rowcnt == 0) {
					//Set Column widths
					FpSpread1.Sheets[0].SetColumnWidth(imagecolnum, 80);
					//Image Column
					FpSpread1.Sheets[0].SetColumnWidth(imagecolnum + 1, 300);
					//Data Column
				}

				//Book title
				model.SetValue(rowcnt, imagecolnum + 1, objDataReader["title"]);
				SetStyleTitle(rowcnt, imagecolnum + 1);

				//Add Book Image
				MakePictureCell(rowcnt, imagecolnum, "book" + bookcnt + ".gif");
				SpanCells(rowcnt, imagecolnum);
				rowcnt = rowcnt + 1;

				//Publisher
				model.SetValue(rowcnt, imagecolnum + 1, "Publisher: " + objDataReader["pub_name"]);
				SetStylePubs(rowcnt, imagecolnum + 1);
				rowcnt = rowcnt + 1;

				//Description
				model.SetValue(rowcnt, imagecolnum + 1, objDataReader["notes"]);
				rowcnt = rowcnt + 1;

				//Price
				if (!Convert.IsDBNull(objDataReader["price"])) {
					//model.SetValue(rowcnt, imagecolnum + 1, "Our Price: " & FormatCurrency(objDataReader("price"), 2))
					unitprice = (decimal)objDataReader["price"];
				} else {
					//model.SetValue(rowcnt, imagecolnum + 1, "Our Price: " & FormatCurrency(0, 2))
					unitprice = 0;
				}
				model.SetValue(rowcnt, imagecolnum + 1, "Our Price: " + Strings.FormatCurrency(unitprice, 2));

				SetStylePrice(rowcnt, imagecolnum + 1);
				rowcnt = rowcnt + 1;

				//Add to Cart
				btnstr = objDataReader["title_id"] + "|" + objDataReader["title"] + "|" + unitprice + "|" + bookcnt;
				MakeButtonCell(rowcnt, imagecolnum + 1, btnstr);
				rowcnt = rowcnt + 2;

				bookcnt = bookcnt + 1;

				if (bookcnt == intbreakcol) {
					//Start second column of books
					rowcnt = 0;
					FpSpread1.Sheets[0].SetColumnWidth(2, 10);
					imagecolnum = 3;
				}
			}

			connection1.Close();

		}

		public int GetRecordCount(string sqlstring)
		{
			//Returns the number of records found
			int reccnt = 0;
      DbConnection connection2 = DBHelper.CreateConnection(sqlConString);
			connection2.Open();
			DbCommand dbCmd = connection2.CreateCommand();
			dbCmd.CommandText = sqlstring;
			reccnt = (int)dbCmd.ExecuteScalar();
			reccnt = reccnt - 1;
			connection2.Close();
			return reccnt;
		}


		public void PopulateCombo()
		{
			//Populate the combo with publishers names
			sqlstr = "SELECT pub_id, pub_name from publishers";

      DbConnection connection3 = DBHelper.CreateConnection(sqlConString);
			connection3.Open();

			DbCommand dbCmd = connection3.CreateCommand();
			dbCmd.CommandText = sqlstr;
			IDataReader objDataReader = dbCmd.ExecuteReader();
			cbPubs.DataTextField = "pub_name";
			cbPubs.DataValueField = "pub_id";
			cbPubs.DataSource = objDataReader;
			cbPubs.DataBind();
			cbPubs.Items.Add("All");

			//Default Selection = All
			cbPubs.SelectedIndex = cbPubs.Items.Count - 1;

			connection3.Close();

		}

		public void MakeButtonCell(int row, int col, string fpid)
		{
			// 'Make a button cell type
			style = new StyleInfo();
			style.Reset();
			///

			//'fpid = ID, Title, Price, Book Picture ID

			ButtonCellType btnType = new ButtonCellType(fpid, FarPoint.Web.Spread.ButtonType.ImageButton, "images/addtocart.gif");
			style.CellType = btnType;
			FpSpread1.ActiveSheetView.SetStyleInfo(row, col, style);

		}

		public void MakePictureCell(int row, int col, string imgUrl)
		{
			// Image cell        
			style = new StyleInfo();
			style.Reset();
			style.CellType = new ImageCellType("images/books/" + imgUrl);
			FpSpread1.ActiveSheetView.SetStyleInfo(row, col, style);

		}

		public void SpanCells(int row, int col)
		{
			FpSpread1.Sheets[0].SpanModel.Add(row, col, 4, 1);
		}

		public void SetStyleTitle(int row, int col)
		{
			//Set the Header Style
			style = new StyleInfo();
			style.Reset();
			style.Font.Size = FontUnit.Point(10);
			style.Font.Bold = true;
			FpSpread1.ActiveSheetView.SetStyleInfo(row, col, style);
		}

		public void SetStylePubs(int row, int col)
		{
			//Set the Publisher Style
			style = new StyleInfo();
			style.Reset();
      style.Font.Size = FontUnit.Point(8);
			style.Font.Italic = true;
			FpSpread1.ActiveSheetView.SetStyleInfo(row, col, style);
		}

		public void SetStylePrice(int row, int col)
		{
			//Set the Publisher Style
			style = new StyleInfo();
			style.Reset();
      style.Font.Size = FontUnit.Point(8);
			style.Font.Bold = true;
			FpSpread1.ActiveSheetView.SetStyleInfo(row, col, style);
		}


		public void InitSpreadStyle()
		{
			style = new StyleInfo();
			style.Reset();
      style.Font.Size = FontUnit.Point(8);
			style.Font.Name = "Verdana";
			FpSpread1.ActiveSheetView.SetStyleInfo(-1, -1, style);
		}

		protected void FpSpread1_ButtonCommand(object sender, FarPoint.Web.Spread.SpreadCommandEventArgs e)
		{
			//fpid = ID, Title, Price, Book Picture ID
			string fpstr = null;
			string[] str2 = new string[4];

			//Store in Array
			fpstr = e.CommandName;

			//Add Item to Cart
			AddToCart(fpstr.Split(new char[] {'|'}));
		}

		public void AddToCart(string[] fpary)
		{
			int i = 0;
			string fpID = null;
			string fpTitle = null;
			string fpPrice = null;
			string fpBookID = null;
			bool ismatch = false;

			//Cart
			if (!Information.IsArray(Session["cart"])) {
				//Init. Shopping Cart
				for (i = 0; i <= Information.UBound(tempcart); i++) {
					tempcart[i, 0] = "";
					//ID
					tempcart[i, 1] = "";
					//Title desc
					tempcart[i, 2] = "0";
					//Unit Price
					tempcart[i, 3] = "0";
					//Qty
					tempcart[i, 4] = "";
					//Book Picture ID
				}

			} else {
				//Assign cart to session variable
				tempcart = (string[,])Session["cart"];
			}

			fpID = fpary[0];
			fpTitle = fpary[1];
			fpPrice = fpary[2];
			if (string.IsNullOrEmpty(fpPrice))
				fpPrice = "0";
			fpBookID = fpary[3];

			//Find the next available spot
			ismatch = false;
			i = 0;
			while (!string.IsNullOrEmpty(tempcart[i, 0]) & i <= Information.UBound(tempcart) & ismatch == false) {
				if (tempcart[i, 0] == fpID) {
					//Already in cart.  Exit loop here to add to quantity
					ismatch = true;
				} else {
					i = i + 1;
				}

			}

			//Add the item
			tempcart[i, 0] = fpID;
			//ID
			tempcart[i, 1] = fpTitle;
			//Title desc
			tempcart[i, 2] = fpPrice;
			//Unit Price
			tempcart[i, 3] = (Convert.ToInt32(tempcart[i, 3]) + 1).ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
			//Qty
			tempcart[i, 4] = fpBookID;
			//Book Picture ID

			//Save new cart
			Session["cart"] = tempcart;

		}


    private void Page_PreRender(object sender, System.EventArgs e)
    {
      //Display the cart
      DisplayCart();
      //Put user code to initialize the page here

      //Turn on/off headers and grid lines
      if (ckShowSpread.Checked == true)
      {
        //Turn On headers
        sscart.Sheets[0].ColumnHeader.Visible = true;
        sscart.Sheets[0].RowHeader.Visible = true;
        sscart.Sheets[0].GridLines = GridLines.Both;
        sscart.Width = System.Web.UI.WebControls.Unit.Pixel(120);

        FpSpread1.Sheets[0].ColumnHeader.Visible = true;
        FpSpread1.Sheets[0].RowHeader.Visible = true;

        FpSpread1.Sheets[0].GridLines = GridLines.Both;

      }
      else
      {
        //Turn Off headers
        sscart.Sheets[0].ColumnHeader.Visible = false;
        sscart.Sheets[0].RowHeader.Visible = false;
        sscart.Sheets[0].GridLines = GridLines.None;
        sscart.Width = System.Web.UI.WebControls.Unit.Pixel(100);

        FpSpread1.Sheets[0].ColumnHeader.Visible = false;
        FpSpread1.Sheets[0].RowHeader.Visible = false;
        FpSpread1.Sheets[0].GridLines = GridLines.None;

      }
    }

		private bool InIE9PlusCompatView()
		{
			if (this.Page.Request.Browser.MajorVersion == 7) {
				string userAgent = this.Page.Request.UserAgent;
				int index = userAgent.IndexOf("trident/", StringComparison.OrdinalIgnoreCase);
				int index2 = 0;
				if (index >= 0) {
					index2 = userAgent.IndexOf(";", index);
				} else {
					index2 = -1;
				}
				if (index2 > index && index >= 0) {
					double tridentVersion = 0;
					if (double.TryParse(userAgent.Substring(index + 8, index2 - (index + 8)), out tridentVersion)) {
						return tridentVersion >= 5;
					}
				}
			}
			return false;
		}

		private System.Collections.IEnumerable GetSpreads(Control ctrl)
		{
			System.Collections.Generic.List<FarPoint.Web.Spread.FpSpread> list = new System.Collections.Generic.List<FarPoint.Web.Spread.FpSpread>();
			foreach (Control c in ctrl.Controls) {
				foreach (FarPoint.Web.Spread.FpSpread spread in GetSpreads(c)) {
					list.Add(spread);
				}

				if (c is FarPoint.Web.Spread.FpSpread) {
					list.Add((FarPoint.Web.Spread.FpSpread)c);
				}
			}

			return list;
		}
  }
}